package com.thx.app.remote.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import mixedserver.protocol.RPCException;
import mixedserver.protocol.jsonrpc.JsonRpcSessionAttributes;

import org.apache.struts2.ServletActionContext;

import com.thx.app.remote.UserInterface;
import com.thx.app.remote.model.RPCExceptionCode;
import com.thx.app.remote.model.RPCResponse;
import com.thx.app.remote.model.User_;
import com.thx.common.spring.BeanFactory;
import com.thx.common.util.EncryptUtil;
import com.thx.common.util.RandomTextUtil;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.WebConstant;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;

public class UserUtil {
	/** 验证码长度默认4 */
	private static int length = 4;

	/**
	 * 自校验接口
	 */
	public interface ValidateListener {
		void checkout() throws RPCException;

	}

	/**
	 * 保存跟项目相关的其他一些信息的接口
	 */
	public interface SaveOtherListener {
		void saveAttribute(	HttpServletRequest request,RPCResponse response);
	}

	/**
	 * 登录
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param validator 验证码
	 * @param checkout 跟项目相关的登录验证接口
	 * @param saveattribute 保存跟项目相关的属性 接口
	 * @return 返回一个RPCLogin_对象 可以通过getAttribute 方法获得对象
	 * @throws RPCException
	 */
	public static RPCResponse login(JsonRpcSessionAttributes session,
			String username, String password, String validator,
			ValidateListener validateListener, SaveOtherListener saveOtherListener)
			throws RPCException {
		RPCResponse response = new RPCResponse();
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User user = userManager.findByName(username);
		if (user == null) throw new RPCException("该用户不存在",RPCExceptionCode.SYSTEM_USER_NO_FOUND);
		
		if (EncryptUtil.checkBybcrypt(password, user.getPassword())) {
			if (validator != null && !validator.equals("")) {
			
				if (!validator.equalsIgnoreCase(session.getAttribute("code") + "")) {
					throw new RPCException("验证码输入错误",RPCExceptionCode.SYSTEM_USER_CAPTCHA_ERROR);
				}
			}
			if (validateListener != null) validateListener.checkout();

			response.setAttribute(UserInterface.SK_USERID, user.getUserId());
			response.setAttribute(UserInterface.SK_USERNAME, user.getUserName());
			response.setAttribute(UserInterface.SK_REALNAME, user.getRealName());
			response.setAttribute(UserInterface.SK_DEPID, user.getDepartment()==null?"":user.getDepartment().getDepId());
			response.setAttribute(UserInterface.SK_DEPNAME, user.getDepartment()==null?"":user.getDepartment().getDepName());
			response.setAttribute(UserInterface.SK_USERLOGO, user.getUserLogo()==null?"":user.getUserLogo());
			response.setAttribute(UserInterface.SK_MOBILE, user.getMobilePhone()==null?"":user.getMobilePhone());


			HttpServletRequest request = getRequest();
			session.setAttribute(WebConstant.KEY_RPC_USER, user);  //session和当前线程的request各放一份
			request.getSession().setAttribute(WebConstant.KEY_RPC_USER, user);
			if (saveOtherListener != null) saveOtherListener.saveAttribute(request,response);
			
			return response;
		} else {
			throw new RPCException("密码输入错误", RPCExceptionCode.SYSTEM_USER_PWD_ERROR);
		}

	}
    /**
     * 在用户登录成功后更新设备号
     * @param username
     * @param deviceId
     * @param imsi
     * @throws RPCException
     */
	public static void updateDeviceId(String username, String deviceId, String imsi){
		if(deviceId == null || deviceId.equals("")) return;
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User u = userManager.findByName(username);
		if (u != null && (u.getDeviceId()==null || !u.getDeviceId().equals(deviceId))) {
			u.setDeviceId(deviceId);
			userManager.update(u);
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param deviceId
	 * @param simCardId
	 * @return
	 * @throws RPCException
	 */
	public static String getCaptcha(JsonRpcSessionAttributes session,
			String deviceId, String simCardId) throws RPCException {
		String[] key = RandomTextUtil.createRandomText(
				RandomTextUtil.Type.alphanumeric, length);
		session.setAttribute("code", key[0]);
		session.setAttribute("deviceId", deviceId);
		session.setAttribute("imsi", simCardId);
		return key[1];
	}

	/**
	 * 修改密码
	 * @return
	 * @throws RPCException
	 */
	public static String changePassword(String userName, String oldPwd, String newPwd) throws RPCException {
		HttpServletRequest request = UserUtil.getRequest();
		User user = (User) request.getSession().getAttribute(WebConstant.KEY_RPC_USER);
		if(!userName.trim().equals(user.getUserName())) throw new RPCException("用户校验失败",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
			
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User olduser = userManager.findByName(userName);
		if (olduser == null) throw new RPCException("该用户不存在",RPCExceptionCode.SYSTEM_USER_NO_FOUND);
		
		if (EncryptUtil.checkBybcrypt(oldPwd, olduser.getPassword())) {
			olduser.setPassword(newPwd);
			olduser.setPwdFormat(null);
			userManager.save(olduser);
			return "";
		}else{
			throw new RPCException("用户名密码错误",RPCExceptionCode.SYSTEM_USER_PWD_ERROR);
		}
	}
	
	/**
	 * 注销操作
	 * @return
	 * @throws RPCException
	 */
	public static boolean logOut(JsonRpcSessionAttributes session) throws RPCException {
		HttpServletRequest request = UserUtil.getRequest();
		session.setAttribute(WebConstant.KEY_RPC_USER, null);
		request.getSession().setAttribute(WebConstant.KEY_RPC_USER,null);
		return true;
	}

	/**
	 * 保存用户信息
	 * 
	 * @param user
	 * @return
	 * @throws RPCException
	 */
	public static boolean saveUserInfor(User_ user) throws RPCException {
		try {
			UserManager userManager = (UserManager) BeanFactory
					.getBean("userManager");
			User u = new User();
			u.setUserName(user.getUserName());
			u.setPassword(user.getPassword());
			u.setCreateDate(new Date());
			u.setStatus(1 + "");
			u.setDeviceId(user.getDeviceId());
			u.setImsi(user.getImsi());
			u.setMobilePhone(user.getMobilePhone());
			userManager.save(u);
			return true;
		} catch (Exception e) {
			throw new RPCException("保存失败！",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
		}
	}
	
	/**
	 * 验证用户session是否存在
	 * @param session
	 * @throws RPCException
	 */
	public static void ValidateSession(HttpServletRequest request) throws RPCException {
		if (request.getSession().getAttribute(WebConstant.KEY_RPC_USER) == null) {
			throw new RPCException("未登录", RPCException.ERROR_CODE_INVALID_SESSION);
		}
	}
	
	/**
	 * 从当前线程获取request
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(WebConstant.CURRENT_REQUEST);
		if (request == null) request = ServletActionContext.getRequest();
		return request;
	}
}
